/**订单支付表 */
const cloud = require('wx-server-sdk')
cloud.init({env: 'evn-cloud-a-4gf1q6iy9df62d73'})
const db = cloud.database()
const MAX_LIMIT = 100

const numberFormat = n => {
  n = n.toString()
  return n[1] ? n : `0${n}`
}
const dateFormatter = date => {
  // const date = new Date()
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const dateStr = `${[year, month, day].map(numberFormat).join('-')}`
  return dateStr
}

const findManyByDateAndStatus = async(event) => {
  console.log('根据日期查询支付明细，输入参数为(event)：', event)
  let date = event.date
  console.log('date: ',date)
  if(date == undefined || date == '' || date == null){
    date = await dateFormatter(new Date())
    console.error('date的值为空：',date)
  }
  console.log('date的值：',date)
  const queryPayDetResult = await db.collection('paymentDetails').where({chargeDate: date, payStatus: '成功'}).count()
  // 先取出集合记录总数
  const total = queryPayDetResult.total
  console.log("根据条件查询数据总条数结束，数据总条数(total)为：",total,'查询总条数返回的结果（queryResult）为：',queryPayDetResult)
  if(total == 0) { 
    return { code: 3001, errMsg: "查询结果为空" }
  }
  const batchTimes = Math.ceil(total / 100)  // 计算需分几次取
  const tasks = []    // 承载所有读操作的 promise 的数组
  for (let i = 0; i < batchTimes; i++) {
    const promise = await db.collection('paymentDetails').where({ chargeDate: date, payStatus: '成功' }).skip(i * MAX_LIMIT).limit(MAX_LIMIT).get({})
    tasks.push(promise)
  }
  console.log('根据条件已查询到数据，合并后的数据(tasks)为：',tasks)
  // 等待所有
  return (await Promise.all(tasks)).reduce((acc, cur) => {
    return { data: acc.data.concat(cur.data), errMsg: acc.errMsg, code: '0000'}
  })
}
/**支付明细表 */
const main = async (event) => {
  const reqType = event.reqType
  switch(reqType){
    case 'findManyByDate':
      return await findManyByDateAndStatus(event)
    default:
      console.error('请求类型不存在.')
      return {code: 2000, errMsg: '请求类型不存在.'}
  }
}
module.exports = {
  main
}